import request from '../../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressInfo: {},
    goodsInfo: [],
    totalMoney: 0,
    userRemark: ''
  },

  /**
   * 地址栏设置
   */
  addressSet() {
    wx.navigateTo({
      url: '/addressPackage/pages/myAddress/myAddress?flag=1'
    })
  },

  /**
   * 获取用户备注
   */
  getUserRemark(options) {
    this.setData({
      userRemark: options.detail.value
    })
  },

  async takeOrder() {
    if (this.data.addressInfo.id == undefined) {
      wx.showToast({
        title: '请先填写好收货地址！',
        icon: 'none'
      })
      return
    }
    let cartIds = [];
    let goodsInfo = this.data.goodsInfo
    for (let goodsIndex in goodsInfo) {
      cartIds.push(goodsInfo[goodsIndex].id)
    }
    let userRemark = this.data.userRemark
    let addressId = this.data.addressInfo.id
    let result = await request("/order/post", {
      addressId,
      userRemark,
      cartIds
    }, 'POST');
    if (result.code == 200) {
      wx.reLaunch({
        url: '/orderPackage/pages/successOrder/successOrder?orderSn=' + result.data,
      })
      return;
    }
    wx.showToast({
      title: '系统繁忙，请稍后再下单！',
      icon: 'none'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    let addressResult = await request("/address/getDefaultAddress");
    if (addressResult.code == 200) {
      this.setData({
        addressInfo: addressResult.data
      })
    };
    let goodsInfo = JSON.parse(options.goodsInfo);
    let totalMoney = this.data.totalMoney
    for (let index in goodsInfo) {
      totalMoney = totalMoney + goodsInfo[index].num * goodsInfo[index].price
    }
    this.setData({
      goodsInfo,
      totalMoney
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(options) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})